<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
    />
    <title>商品搜索</title>
    <link rel="stylesheet" href="./iconfont/fonts/iconfont.css" />
    <link rel="stylesheet" href="./css/goodsSearch.css" />
    <link rel="stylesheet" href="./css/base.css">
  </head>

  <body>
    <div class="header">
      <span
        class="iconfont icon-zuojiantou"
        onclick="window.history.go(-1);"
      ></span>
      <p>商品搜索</p>
    </div>
    <div class="search">
      <input type="text" name="goodsName" placeholder="请输入您搜索的商品" />
      <div><a href="javaScript:;" class="searchBtn">搜索</a></div>
    </div>
    <div class="centent">
      <div class="title">
        <div class="left">最近搜索</div>
        <i class="iconfont icon-shanchu"></i>
      </div>
      <div class="main"></div>
    </div>
    <script>
      const inputDom = document.querySelector("[name=goodsName]")

      let searchHistory =
        JSON.parse(localStorage.getItem("searchHistory")) || []
      renderMain()

      document.querySelector(".searchBtn").addEventListener("click", () => {
        if (inputDom.value === "") {
          return
        }
        location.href = `./搜索列表.html?search=${inputDom.value}`

        if (inputDom.value !== "") searchHistory.unshift(inputDom.value)

        let newArr = [...new Set(searchHistory)]
        localStorage.setItem("searchHistory", JSON.stringify(newArr))
        renderMain()

        inputDom.value = ""
      })

      document.querySelector(".main").addEventListener("click", (e) => {
        if (e.target.classList.contains("search-item")) {
          location.href = `./搜索列表.html?search=${e.target.innerHTML}`
        }
      })
      function renderMain() {
        if (searchHistory.length !== 0) {
          searchHistory
            ? (document.querySelector(".main").innerHTML = searchHistory
                .map((item) => `<div class="search-item">${item}</div>`)
                .join(""))
            : (document.querySelector(".main").innerHTML = "")
        }
      }


      document.querySelector('.icon-shanchu').addEventListener('click',function () {
        localStorage.removeItem('searchHistory')
        location.reload() // 刷新
      })
    </script>
  </body>
</html>
